<?php
namespace app\admin\controller;
// use think\Controller;
use think\Db;
use think\Request;
use think\Cache;
use think\Cookie;
use think\Session;
use think\captcha\Captcha;
use \app\admin\model\Users as m;
class Products extends Common
{
    public function index()
    {
        // 控制器模块
        // $this->assign('controller',Request()->controller());
        // $this->assign('module',Request()->module());
        // $this->assign('action',Request()->action());



        $pid=input('pid',0);
        $ty=input('ty',0);
        $tty=input('tty',0);
        $ttty=input('ttty',0);
        $q=input('q',"");

        $addurl="/admin/products/add";
        $pagesize=input('pagesize',0);
        if($pagesize){
            $_SESSION['pagesizes']=$pagesizes=$pagesize;
        }else{
            if(isset($_SESSION['pagesizes'])){
                $pagesizes=$_SESSION['pagesizes'];
            }else{
                $pagesizes=10;
            }
        }
        if($ttty>0){
            $zid=$ttty;
        }elseif($tty>0){
            $zid=$tty;
        }elseif($ty>0){
            $zid=$ty;
        }elseif($pid>0){
            $zid=$pid;
        }

        $vs['pid']=$pid;
        $vs['ty']=$ty;
        $vs['tty']=$tty;
        $vs['ttty']=$ttty;
        $vs['zid']=$zid;

        $vs['listurl']=url('products/index',"pid={$pid}&ty={$ty}&tty={$tty}&ttty={$ttty}");
        $vs['addurl']=url('products/add',"pid={$pid}&ty={$ty}&tty={$tty}&ttty={$ttty}");
        $vs['catname']=get_sort_zd($zid);
        $vs['imgnum']=get_sort_zd($zid,'imgnum');

        if($pid){$map['pid']=$pid;$addurl.="/pid/".$pid;}
        if($ty){$map['ty']=$ty;$addurl.="/ty/".$ty;}
        if($tty){$map['tty']=$tty;$addurl.="/tty/".$tty;}
        if($ttty){$map['ttty']=$ttty;$addurl.="/ttty/".$ttty;}
        if($q) $map['title']=array('like',"%$q%");
        $list=Db::name("products")->where($map)->order("disorder desc,sendtime desc,id desc")->paginate($pagesizes);

        $model_id=get_sort_zd($zid,'model_id');//获取当前栏目模块id

        $model_fields=get_model_zd($model_id,'model_fields');
        $arr=explode(",",$model_fields);

        $this->assign("pid",$pid);
        $this->assign("ty",$ty);
        $this->assign("arr",$arr);
        $this->assign("pagesizes",$pagesizes);

        $this->assign("list",$list);
        $this->assign("addurl",$addurl);
        $this->assign('vs',$vs);
        return $this->fetch("/products/index");
    }


    //添加
    public function add()
    {
        // Cache::set('url',$_SERVER['HTTP_REFERER'])
        $id=input('id',0);
        $pid=input('pid',0);
        $ty=input('ty',0);
        $tty=input('tty',0);
        $ttty=input('ttty',0);

        if($id){
            $v=Db::name("products")->find($id);
            $pid=$v['pid'];
            $ty=$v['ty'];
            $tty=$v['tty'];
            $ttty=$v['ttty'];
        }
        $url="/admin/products/index";

        if($ttty>0){
            $zid=$ttty;
        }elseif($tty>0){
            $zid=$tty;
        }elseif($ty>0){
            $zid=$ty;
        }elseif($pid>0){
            $zid=$pid;
        }
        if($pid){$url.="/pid/".$pid;}
        if($ty){$url.="/ty/".$ty;}
        if($tty){$url.="/tty/".$tty;}
        if($ttty){$url.="/ttty/".$ttty;}
        $url.=".html";
        $v=Db::name("products")->find($id);

        if($v['id']){
            $v['pid']=$v['pid'];
            $v['ty']=$v['ty'];
            $v['tty']=$v['tty'];
            $v['ttty']=$v['ttty'];
            $v['ttyt']=$v['ttty'];
            $v['catname']=get_sort_zd($zid);
            $v['imgnum']=get_sort_zd($zid,'imgnum');
        }else{
            $v['pid']=$pid;
            $v['ty']=$ty;
            $v['tty']=$tty;
            $v['ttty']=$ttty;
            $v['title']='';
            $v['seokeywords']="";
            $v['seodescription']="";
            $v['content']="";
            $v['introduce']='';
            $v['img1']='';
            $v['img2']='';
            $v['isgood']='';
            $v['istop']='';
            $v['id']=0;
            $v['imgnum']=0;
            $v['hits']=0;
            $v['status']=1;
            $v['model_id']=1;
            $v['fahuotype']=1;
            $v['pid']=$pid;
            $v['disorder']=0;
            $v['sendtime']=time();
        }

        $v['pid']=$pid;
        $v['ty']=$ty;
        $v['tty']=$tty;
        $v['ttty']=$ttty;
        $v['zid']=$zid;
        $v['listurl']=url('products/index',"pid={$pid}&ty={$ty}&tty={$tty}&ttty={$ttty}");
        $v['addurl']=url('products/add',"pid={$pid}&ty={$ty}&tty={$tty}&ttty={$ttty}");
        $v['catname']=get_sort_zd($zid);
        $v['imgnum']=get_sort_zd($zid,'imgnum');

        $map1['pid']=$id;
        $imglist=Db::name("titlepic")->where($map1)->order("disorder desc,sendtime desc")->select();
        //print_r($imglist);


        if(Request::instance()->isPost()){
            $data=$_POST;
            $data['updatesendtime']=time();
            $data['status']=1;
            // dump($data);die;
            // -----------1产品详情轮播图--------------
                $ids = request()->post('ids/a');
                $imgurl = request()->post('imgurl/a');
                $tit = request()->post('tit/a');
                $imgurl=isset($imgurl)?$imgurl:0;
                if($imgurl){
                    // dump(count($imgurl));
                    $titlepic = Db::name("titlepic");
                    $data1 = array();
                    for ($i=0; $i < count($imgurl); $i++) { 
                        $data1[$i]['pid']=$id;
                        $data1[$i]['ty']=$ty;
                        $data1[$i]['tty']=$tty;
                        $data1[$i]['ttty']=$ttty;
                        // $data1[$i]['title']=$tit[$i];
                        $data1[$i]['img1']=$imgurl[$i];
                        $data1[$i]['status']=1;
                        $data1[$i]['type']=0;
                        if(!$ids[$i]){
                            $data1[$i]['sendtime']=time();
                            $titlepic->insert($data1[$i]);
                        }else{
                            $data1[$i]['id']=$ids[$i];
                            $titlepic->update($data1[$i]);
                        }
                        // dump($data1[$i]);die();
                    }
                    unset($data['ids']);
                    unset($data['imgurl']);
                    unset($data['tit']); 
                }
            // ----------------结束------------------
            // -----------2产品图文详情--------------
                $wt_ids = request()->post('wt_ids/a');
                $wt_imgurl = request()->post('wt_imgurl/a');
                $wt_tit = request()->post('wt_tit/a');
                $wt_imgurl=isset($wt_imgurl)?$wt_imgurl:0;
                if($wt_imgurl){
                    // dump(count($wt_imgurl));die();
                    $titlepic = Db::name("titlepic");
                    $data1 = array();
                    for ($i=0; $i < count($wt_imgurl); $i++) { 
                        $data1[$i]['pid']=$id;
                        $data1[$i]['ty']=$ty;
                        $data1[$i]['tty']=$tty;
                        $data1[$i]['ttty']=$ttty;
                        // $data1[$i]['title']=$wt_tit[$i];
                        $data1[$i]['img1']=$wt_imgurl[$i];
                        $data1[$i]['status']=1;
                        $data1[$i]['type']=1;
                        // dump($data1[$i]);die();
                        if(!$wt_ids[$i]){
                            $data1[$i]['sendtime']=time();
                            $titlepic->insert($data1[$i]);
                        }else{
                            $data1[$i]['id']=$wt_ids[$i];
                            $titlepic->update($data1[$i]);
                        }
                        // dump($data1[$i]);die();
                    }
                    unset($data['wt_ids']);
                    unset($data['wt_imgurl']);
                    unset($data['wt_tit']); 
                }
            // ----------------结束------------------

            if($data['id']){
                //print_r($data);
                $result=@Db::name("products")->update($data);
                if($result){
                    
                    $catname=get_zd_name("catname","sort","id=".$zid);
                    $this->sys_log("编辑{$catname}栏目内容:{$v['title']}(id:$id)");
                    $this->success("修改成功",$url);

                }else{
                    $this->error("修改失败");
                }
            }else{
                $data['sendtime']=time();
                if(Db::name("products")->insert($data)){
                    $catname=get_zd_name("catname","sort","id=".$zid);
                    $this->sys_log("添加{$catname}栏目内容:{$v['title']}(id:$id)");
                    $this->success("添加成功",$url);

                }else{
                    $this->error("添加失败");
                }
            }
        }
        $v['imgnum']=get_sort_zd($zid,'imgnum')+1;
        $v['imgtype']=get_sort_zd($zid,'imgtype');
        $model_id=get_sort_zd($zid,'model_id');//获取当前栏目模块id
        $model_fields=get_model_zd($model_id,'model_fields');
        $arr=explode(",",$model_fields);

        // print_r($arr);die;
        $this->assign("arr",$arr);
        $this->assign("imglist",$imglist);
        $this->assign("v",$v);
        $this->assign("url",$url);
        // print_r($v);

        return $this->fetch("/products/add");
    }

    //删除
    public function del()
    {
        $id=input('id',0);
        // die();
        $v=Db::name("products")->find($id);
        if(Db::name("products")->delete($id)){
//        if(1){
            $url="/admin/products/index";
            if($v['pid'])$url.="/pid/".$v['pid'];
            if($v['ty'])$url.="/ty/".$v['ty'];
            if($v['tty'])$url.="/tty/".$v['tty'];
            if($v['ttty'])$url.="/ttty/".$v['ttty'];
            if(file_exists(substr($v['img1'],1))){
                unlink(substr($v['img1'],1));
            }
            $this->sys_log("删除新闻:(id:$id)");
            $this->success("删除成功",$url);
        }else{
            $this->error("删除失败");
        }
    }


    public function Titlepic()
    {
        $id=input('id',0);
        $imgUrl=input('imgUrl',0);
        if($id){
            $v=Db::name("titlepic")->find($id);
            if(file_exists(substr($v['img1'],1))){
                // die(substr($v['img1'],1));
                unlink(substr($v['img1'],1));
                Db::name("titlepic")->delete($id);
            }
        }else{
            if(file_exists(substr($imgUrl,1))){
                unlink(substr($imgUrl,1));
            }
        }
    }
    public function action()
    {
        $url=$_SERVER['HTTP_REFERER'];
        $act=$_POST['act'];
        $sorting_arr=$_POST['sorting'];
        $checkid=$_POST['checkid'];
        // print_r($checkid);
        // print_r($_POST);
        // die;
        if($act=='sorting'){
            for($i=0;$i<count($checkid);$i++) {
                Db()->execute("update ".config('database.prefix')."products set disorder=$sorting_arr[$i] where id='{$checkid[$i]}'");
                $this->sys_log("信息排序更新:(id:$checkid[$i])");
            }
            $this->success("信息排序更新成功",$url);
        }elseif($act=='alldel') {
            for($i=0;$i<count($checkid);$i++) {
                $this->sys_log("删除信息:(id:$checkid[$i])");
                Db::name("products")->delete($checkid[$i]);
            }
            $this->success("信息删除成功",$url);
        }elseif($act=='isgood'||$act=='istop') {
            for($i=0;$i<count($checkid);$i++) {
                $v=Db::name("products")->find($checkid[$i]);
                $data[$act]=$v[$act]?0:1;
                Db::name("products")->where("id=".$checkid[$i])->update($data);
               $this->sys_log("删除信息:(id:$checkid[$i])");
            }
            $this->success("操作成功",$url);
        }

    }

    //审核
    public function audit()
    {
        $url=$_SERVER['HTTP_REFERER'];
        $id=input('id');
        $zd='status';
//        print_r($_POST);
        $v=Db::name("products")->find($id);
        $data[$zd]=$v[$zd]?0:1;

        if(Db::name("products")->where("id=".$id)->update($data)){
           $this->success("审核成功",$url);
            // $return_data['status'] = 0;
            // $return_data['msg'] ="审核成功";
        }else{
           $this->error("审核失败",$url);
            // $return_data['status'] = 1;
            // $return_data['msg'] ="审核失败";
        }
//
        // echo json_encode($return_data);


    }


    //添加
    public function single()
    {
        $id=input('id',0);
        $pid=input('pid',0);
        $ty=input('ty',0);
        $tty=input('tty',0);
        $ttty=input('ttty',0);

        if($id){
            $v=Db::name("products")->find($id);
            $pid=$v['pid'];
            $ty=$v['ty'];
            $tty=$v['tty'];
            $ttty=$v['ttty'];
        }
        $url="/admin/products/single";

        if($ttty>0){
            $zid=$ttty;
        }elseif($tty>0){
            $zid=$tty;
        }elseif($ty>0){
            $zid=$ty;
        }elseif($pid>0){
            $zid=$pid;
        }

        if($pid){$url.="/pid/".$pid;$map['pid']=$pid;}
        if($ty){$url.="/ty/".$ty;$map['ty']=$ty;}
        if($tty){$url.="/tty/".$tty;$map['tty']=$tty;}
        if($ttty){$url.="/ttty/".$ttty;$map['ttty']=$ttty;}
        $url.=".html";
        $v=Db::name("products")->where($map)->find();

        if($v['id']){
            $v['pid']=$v['pid'];
            $v['ty']=$v['ty'];
            $v['tty']=$v['tty'];
            $v['ttty']=$v['ttty'];
            $v['ttyt']=$v['ttty'];
        }else{
            $v['pid']=$pid;
            $v['ty']=$ty;
            $v['tty']=$tty;
            $v['ttty']=$ttty;
            $v['id']=0;
            $v['title']="";
            $v['ftitle']="";
            $v['linkurl']="";
            $v['introduce']="";
            $v['seotitle']="";
            $v['seokeywords']="";
            $v['seodescription']="";
            $v['content']="";
            $v['sort_a']="";
            $v['imgnum']=0;
            $v['imgsize']="";
            $v['file1']="";
            $v['source']="";
            $v['author']="";
            $v['price']="";
            $v['hits']=0;
            $v['img1']="";
            $v['img2']="";
            $v['status']=1;
            $v['model_id']=1;
            $v['pid']=$pid;

            $v['disorder']=0;
            $v['sendtime']=time();

        }

        $v['catname']=get_sort_zd($zid);
        if(Request::instance()->isPost()){
            $data=$_POST;
            
            $data['sendtime']=strtotime($_POST['sendtime']);
            if($v['id']){
                if(Db::name("products")->update($data)){


                    $this->sys_log("编辑{$v['catname']}栏目内容:{$v['title']}(id:$id)");
                    $this->success("修改成功",$url);
                }else{
                    $this->error("修改失败");
                }
            }else{
                $data['sendtime']=time();
                if(Db::name("products")->insert($data)){
                    $this->success("添加成功",$url);
                }else{
                    $this->error("添加失败");
                }
            }
        }
        $v['imgnum']=get_sort_zd($zid,'imgnum')+1;
//        die;
        $model_id=get_sort_zd($zid,'model_id');//获取当前栏目模块id
        $model_fields=get_model_zd($model_id,'model_fields');
        $arr=explode(",",$model_fields);


        $this->assign("arr",$arr);
        $this->assign("v",$v);


        return $this->fetch("/products/single");
    }

    public function barcode_create(){
        $content='123';
        // 引用barcode文件夹对应的类
        include './extend/BCode/BCGFontFile.php';
        //Loader::import('BCode.BCGFontFile',EXTEND_PATH);
        //Loader::import('BCode.BCGColor',EXTEND_PATH);
        //Loader::import('BCode.BCGDrawing',EXTEND_PATH);
        include './extend/BCode/BCGDrawing.php';
        // 条形码的编码格式
        //Loader::import('BCode.BCGcode39',EXTEND_PATH,'.barcode.php');
        include './extend/BCode/BCGcode39.barcode.php';
        // $code = '';
        // 加载字体大小
        //$font = new BCGFontFile('./class/font/Arial.ttf', 18);
        //颜色条形码
        $color_black = new \BCGColor(0, 0, 0);
        $color_white = new \BCGColor(255, 255, 255);
        $drawException = null;
        try
        {
            $code = new \BCGcode39();
            $code->setScale(2);
            $code->setThickness(30); // 条形码的厚度
            $code->setForegroundColor($color_black); // 条形码颜色
            $code->setBackgroundColor($color_white); // 空白间隙颜色
            // $code->setFont($font); //
            $code->parse($content); // 条形码需要的数据内容
        }
        catch(\Exception $exception)
        {
            $drawException = $exception;
        }
        //根据以上条件绘制条形码
        $drawing = new \BCGDrawing('', $color_white);
        if($drawException) {
            $drawing->drawException($drawException);
        }else{
            $drawing->setBarcode($code);
            $drawing->draw();
        }
        // 生成PNG格式的图片
        header('Content-Type: image/png');
         // header('Content-Disposition:attachment; filename="barcode.png"'); //自动下载
        $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
        //$a= $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
        //echo "< img src='{$a}'>";
    }

    public function barcodegen(){
        // dump($class_dir);
        // dump(is_file(VENDOR_PATH.'barcodegen/html/header.php'));
        // die;
        // vendor('barcodegen.class.BCGFontFile');
        // require "../../../../barcodegen/class/BCGFontFile.php";
        include "./extend/barcodegen/class/BCGFontFile.php";
        // vendor('barcodegen.class.BCGColor',VENDOR_PATH,'.class.php');
        // vendor('barcodegen.class.BCGColor');
        // vendor('barcodegen.class.BCGDrawing');
        // vendor('barcodegen.class.BCGDrawing',VENDOR_PATH,'.class.php');
        include "./extend/barcodegen/class/BCGDrawing.php";

        // Including the barcode technology
        include('./extend/barcodegen/class/BCGcode39.barcode.php');

        // Loading Font
        $font = new \BCGFontFile('./extend/barcodegen/class/font/Arial.ttf', 18);

        // The arguments are R, G, B for color.
        $color_black = new \BCGColor(0, 0, 0);
        $color_white = new \BCGColor(255, 255, 255);

        $code = new \BCGcode39();//dump($font);die();
        $code->setScale(2); // Resolution
        $code->setThickness(30); // Thickness
        $code->setForegroundColor($color_black); // Color of bars
        $code->setBackgroundColor($color_white); // Color of spaces
        $code->setFont($font); // Font (or 0)
        $code->parse('HELLO'); // Text


        /* Here is the list of the arguments
        1 - Filename (empty : display on screen)
        2 - Background color */
        $drawing = new \BCGDrawing('', $color_white);
        $drawing->setBarcode($code);
        $drawing->draw();

        // Header that says it is an image (remove it if you save the barcode to a file)
        header('Content-Type: image/png');
        header('Content-Disposition:attachment; filename="barcode.png"');
        // Draw (or save) the image into PNG format.
        $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
    }
    //上传图片
    public function uploads()
    {

        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $path=ROOT_PATH . 'Uploads' . DS . 'images';
            $info = $file->rule('date')->move($path);
//            print_r($info);
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $return_data['status'] = 0;
                $path1= '/Uploads/images';
                $getSaveName=str_replace("\\","/",$info->getSaveName());
                $return_data['msg'] =$path1.'/'.$getSaveName;
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }

            echo json_encode($return_data);

        }
    }
}